<template>
  <div>
    <el-popover
      ref="popoverRef"
      :visible="visible"
      placement="bottom"
      :width="600"
      trigger="click"
      @before-enter="handleShow"
    >
      <template #default>
        <div
          id="panel"
          v-click-outside="onClickOutside"
          class="panel no-select"
          @mouseleave="handleMouseleave"
        >
          <div class="box">
            <div class="yearrange-header">
              <span
                class="prev-btn"
                @click="handlePrevBtn"><el-icon><DArrowLeft /></el-icon></span>
              <span
                v-cloak
                class="title">{{ leftTitle }}</span>
            </div>
            <div class="yearrange-table">
              <table class="w100 el-year-table">
                <tbody>
                  <tr
                    v-for="(item, index) in leftData"
                    :key="index">
                    <td
                      v-for="(ite, ind) in item"
                      :key="ind"
                      :class="{
                        active: startYear === ite || endYear === ite,
                        disabled: now.getFullYear() < ite
                      }"
                      @click="() => handleTd(index, ind, ite)"
                      @mouseenter="() => handleMouseenter(ite)"
                    >
                      <div
                        :class="{
                          'el-date-table-cell': true,
                          hover:
                            (ite >= (startYear === undefined ? 0 : startYear) &&
                              ite <= hoverYear) ||
                            (ite <= (startYear === undefined ? 0 : startYear) &&
                              ite >= hoverYear &&
                              hoverYear !== 0)
                        }"
                      >
                        <span
                          v-cloak
                          class="cell">{{ ite }}</span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="box">
            <div class="yearrange-header">
              <span
                v-cloak
                class="title">{{ rightTitle }}</span>
              <span
                class="next-btn"
                @click="handleNextBtn"><el-icon><DArrowRight /></el-icon></span>
            </div>
            <div class="yearrange-table">
              <table class="w100 el-year-table">
                <tbody>
                  <tr
                    v-for="(item, index) in rightData"
                    :key="index">
                    <td
                      v-for="(ite, ind) in item"
                      :key="ind"
                      :class="{
                        active: startYear === ite || endYear === ite,
                        disabled: now.getFullYear() < ite
                      }"
                      @click="() => handleTd(index, ind, ite)"
                      @mouseenter="() => handleMouseenter(ite)"
                    >
                      <div
                        :class="{
                          'el-date-table-cell': true,
                          hover:
                            (ite >= (startYear === undefined ? 0 : startYear) &&
                              ite <= hoverYear) ||
                            (ite <= (startYear === undefined ? 0 : startYear) &&
                              ite >= hoverYear &&
                              hoverYear !== 0)
                        }"
                      >
                        <span
                          v-cloak
                          class="cell">{{ ite }}</span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </template>
      <template #reference>
        <el-input
          v-model="yearRange"
          :prefix-icon="Calendar"
          @click="() => (visible = true)" />
      </template>
    </el-popover>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, toRaw } from 'vue'
import { DArrowLeft, DArrowRight, Calendar } from '@element-plus/icons-vue'
import { ClickOutside as vClickOutside } from 'element-plus'
const leftData = ref<Array<number>[]>([])
const leftTitle = ref<string>()
const rightData = ref<Array<number>[]>([])
const rightTitle = ref<string>()

const daterange = ref<any>() // [number, number]
const startYear = ref<number>()
const endYear = ref<number>()
const hoverYear = ref<number>(0)

const visible = ref(false)
const now = new Date()
let currentYear = now.getFullYear()

const popoverRef = ref()
const yearRange = computed(() => {
  if (!daterange.value || daterange.value.length !== 2) return ''
  return `${daterange.value[0]} - ${daterange.value[1]}`
})

const computedLeft = () => {
  leftData.value = []
  rightData.value = []
  const start = Math.floor(currentYear / 10) * 10
  const end = start + 10
  leftTitle.value = `${start} 年 - ${end - 1} 年`
  rightTitle.value = `${start + 10} 年 - ${end + 9} 年`
  let leftRow = []
  let rightRow = []
  for (let i = start; i < end; i++) {
    if ((i - start) % 4 === 0) {
      leftData.value.push(leftRow)
      rightData.value.push(rightRow)
      leftRow = []
      rightRow = []
    }
    leftRow.push(i)
    rightRow.push(i + 10)
  }
  leftData.value.push(leftRow)
  rightData.value.push(rightRow)
  console.log('leftData:', leftData, start, end)
}
computedLeft()
// const clearTdClass = () => {
//   const tds = document.getElementsByTagName('td')
//   const actives = []
//   for(let i = 0, len = tds.length; i < len; i ++) {
//     if(tds[i].className === 'active') {
//       actives.push(tds[i])
//     }else{
//       tds[i].className = ''
//     }
//   }
//   if(actives.length === 2) {
//     actives.forEach(ele => {
//       ele.className = ''
//     })
//   }
// }
const handleTd = (row: number, col: number, ite: number) => {
  if (ite > now.getFullYear()) return
  // clearTdClass();
  // (e.currentTarget as any).className = 'active'
  if (!daterange.value || daterange.value?.length === 2) {
    daterange.value = []
    startYear.value = undefined
    endYear.value = undefined
    hoverYear.value = 0
  }
  daterange.value.push(ite)
  daterange.value.sort((a: number, b: number) => a - b)
  console.log('daterange:', daterange.value)
  if (daterange.value.length === 2) {
    hoverYear.value = 0
    visible.value = false
    startYear.value = toRaw(daterange.value)[0]
    endYear.value = toRaw(daterange.value)[1]
  } else if (daterange.value.length === 1) {
    startYear.value = toRaw(daterange.value)[0]
  }
}

const handleShow = () => {
  if (!daterange.value || !daterange.value || daterange.value.length !== 2) return
  startYear.value = toRaw(daterange.value)[0]
  hoverYear.value = toRaw(daterange.value)[1]
}

const onClickOutside = () => {
  visible.value = false
}
const handlePrevBtn = () => {
  if (currentYear < 1900) return
  currentYear -= 10
  computedLeft()
}
const handleNextBtn = () => {
  if (currentYear > 2300) return
  currentYear += 10
  computedLeft()
}
const handleMouseenter = (ite: number) => {
  if (daterange.value && daterange.value && daterange.value.length === 2) return
  if (ite > now.getFullYear()) return (hoverYear.value = 0)
  if (daterange.value && daterange.value && daterange.value.length === 1) hoverYear.value = ite
}
const handleMouseleave = () => {
  if (daterange.value && daterange.value && daterange.value.length === 1) hoverYear.value = 0
}
// // const handleRightTd = (row: number, col: number, ite: number) => {
// //   endActive.value = `${row},${col}`
// //   endDate.value = ite
// // }

// const getRowCol = (num: number) => {
//   const mod = num % 10
//   const row = Math.ceil(mod / 4)
//   const col = mod % 4
//   return {
//     row,
//     col
//   }
// }
// const handleBeforeEnter = () => {
//   if (!yearRange.value) {
//     startActive.value = ''
//     endActive.value = ''
//   } else {
//     startDate.value = Number(yearRange.value.split('-')[0])
//     endDate.value = Number(yearRange.value.split('-')[1])
//     const startRowCol = getRowCol(startDate.value)
//     const endRowCol = getRowCol(endDate.value)
//     startActive.value = `${startRowCol.row},${startRowCol.col}`
//     endActive.value = `${endRowCol.row},${endRowCol.col}`
//     console.log('---', startActive.value, endActive.value)
//   }
// }

// const handleAfterEnter = () => {

// }
</script>

<style lang="scss" scoped>
$color: #29f1fa;
.yearrange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  padding-right: 5px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  height: 30px;
  position: relative;
  text-align: center;
  .title {
    display: block;
    width: 100%;
    cursor: pointer;
    &:hover {
      color: $color;
    }
  }
  .prev-btn {
    position: absolute;
    left: 0;
  }
  .prev-btn,
  .next-btn {
    cursor: pointer;
    &:hover {
      color: $color;
    }
  }
}
.el-year-table td:hover {
  color: $color;
}
.panel {
  display: flex;
  .box {
    flex: 1;
    padding-left: 10px;
    padding-right: 10px;
    & + .box {
      border-left: 1px solid #ebeef5;
    }
  }
}
.el-date-table-cell.hover {
  background-color: #f2f6fc;
}
.active {
  span {
    background-color: $color;
    border-radius: 50%;
    width: 36px;
    height: 36px;
    line-height: 36px;
    display: block;
    color: #fff;
    &:hover {
      color: #fff;
    }
  }
}
.el-year-table td {
  padding-left: 0;
  padding-right: 0;
}
:deep(.el-input__wrapper) {
  background: transparent;
  .el-input__inner {
    color: #fff;
  }
}
</style>
